package no02;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/5/20 11:24
 * II 二进制加法
 * https://leetcode.cn/problems/JFETK5/
 */
public class Solution {

    public String addBinary(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        int carry = 0; // 表示进位
        int num = 0; // 表示每一位数字运算后的值
        char[] num1Char = num1.toCharArray();
        char[] num2Char = num2.toCharArray();
        int index1 = num1Char.length - 1;
        int index2 = num2Char.length - 1;
        while (index1 >= 0 || index2 >= 0 || carry != 0) {
            int curNum1 = index1 >= 0 ? (num1Char[index1] - '0') : 0;
            int curNum2 = index2 >= 0 ? (num2Char[index2] - '0') : 0;
            num = curNum1 + curNum2 + carry;
            int itemNum = num % 2;
            carry = num / 2;
            res.append(itemNum);
            --index1;
            --index2;
        }

        double random = Math.random();
        return res.reverse().toString();
    }
}
